package com.waypolice.common.utils;

import org.apache.shiro.SecurityUtils;

import javax.servlet.http.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * session监听(获取当前登录用户数工具类)
 * @author wr
 *
 */
public class SessionListener implements HttpSessionListener{
	
	private static final String LOGIN_URL="/sessionrun.jsp";
	public static HashMap<String,HttpSession> sessionMap = new HashMap<String,HttpSession>();
	
	@Override
	public void sessionCreated(HttpSessionEvent se) {

	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		HttpSession session = se.getSession();
		String ppStrone = (String) session.getAttribute("USERSTRONE_SESSION");
		SessionListener.sessionMap.remove(ppStrone);
	}

	public static int getCount(){
		return sessionMap.size();
	}
	
	  /*

     * isAlreadyEnter-用于判断用户是否已经登录以及相应的处理方法

     * @param sUserName String-登录的用户名称

     * @return boolean-该用户是否已经登录过的标志

     */
    public static boolean isAlreadyEnter(HttpServletResponse response,
			HttpServletRequest request,HttpSession session,String sUserName) throws Exception{
        boolean flag = false;
        if(sessionMap.containsKey(sUserName)){//如果该用户已经登录过，则使上次登录的用户掉线(依据使用户名是否在hUserName中)
        	flag = true;
        	try {
            HttpSession httpSession = sessionMap.get(sUserName);
        		httpSession.invalidate();
            //遍历原来的hUserName，删除原用户名对应的sessionID(即删除原来的sessionID和username)
            Iterator iter = sessionMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry)iter.next();
                Object key = entry.getKey();
                Object val = entry.getValue();
                if( ( (String)key ).equals(sUserName) ){
                	sessionMap.remove(key);
					SecurityUtils.getSubject().logout();
                }
            }
            sessionMap.put(sUserName, session);//添加现在的sessionID和username
        	} catch (Exception e) {
        		boolean aaa = sessionMap.containsKey(sUserName);
        		if (aaa) {
        			sessionMap.remove(sUserName);
        			 sessionMap.put( sUserName,session );
			         return flag;
				}else {
					  flag = false;
			          sessionMap.put( sUserName,session );
			          return flag;
				}
        		// response.sendRedirect(request.getContextPath()+"/login");
        		//response.sendRedirect(request.getSession().getServletContext().getContextPath()+LOGIN_URL);
        	}
        }else{//如果该用户没登录过，直接添加现在的sessionID和username
            flag = false;
            sessionMap.put( sUserName,session );
        }
        return flag;
    }
}
